package com.hgq.jssjyyxt.controller;

import com.hgq.jssjyyxt.util.DateUtil;
import com.hgq.jssjyyxt.util.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.MailSendException;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.mail.Address;
import javax.mail.MessagingException;
import javax.mail.SendFailedException;
import javax.mail.internet.MimeMessage;
import javax.servlet.http.HttpServletRequest;
import java.io.UnsupportedEncodingException;
import java.util.HashSet;
import java.util.Set;


@Slf4j
@RestController
@RequestMapping("email")
public class EmailController {

    @Resource
    private JavaMailSender mailSender;

    @Value("${send-email}")
    private String email;

    /**
     * 发送邮箱
     *
     * @param email 条件
     * @return 登录状态
     */
    @PostMapping("yanzhengma")
    public Result yanzhengma(HttpServletRequest request, String email) throws MessagingException, UnsupportedEncodingException {
        try {
            String subject = "验证码";
            int i = sendSimpleMails(email, subject,true, subject);
            if (i != 1) {
                return Result.failure("发送失败，请查看邮箱是否正确.");
            }
            return Result.success("发送成功,请注意查收！！！");
        } catch (MailSendException e) {
            Set<String> tmpInvalidMails = getInvalidAddress(e);
            // 非无效收件人导致的异常，暂不处理
            if (tmpInvalidMails.isEmpty()) {
                log.error(e.getMessage());
                return Result.failure("发送失败，请查看邮箱是否正确.");
            }
            return Result.failure("发送失败，系统故障，请联系管理员");
        }
    }

    /**
     * @param to        收件人
     * @param subject   主题
     * @param isSuccess 是否通过
     * @return
     * @throws MessagingException
     * @throws UnsupportedEncodingException
     */
    public int sendSimpleMails(String to, String subject, boolean isSuccess, String msg) throws MessagingException, UnsupportedEncodingException {
        try {
            MimeMessage mimeMessage = mailSender.createMimeMessage();
            MimeMessageHelper mimeMessageHelper = new MimeMessageHelper(mimeMessage, true);
            //发件人  别名
            mimeMessageHelper.setFrom(email, "scj");
            //收信人
            mimeMessageHelper.setTo(to);
            //主题
            mimeMessageHelper.setSubject(subject);
            if (isSuccess) {
                //文本
                mimeMessageHelper.setText("<!DOCTYPE html><html><head><meta charset='utf-8'><title></title></head><body>" +
                        "<table>" +
                        "<tr><th>欢迎注册健身私教预约系统</th></tr>" +
                        "<tr><td>教练您好，您正在注册健身私教预约系统，已查验你提交的注册材料，经过审核注册成功。</td></tr>" +
                        "<tr><td>欢迎进行登录，进行填写个人资料，就可以发布课程进行教学了。</td></tr>" +
                        "<tr><td>现在时间：" + DateUtil.getTime() + "</td></tr>" +
                        "</table></body></html>", true);
            } else {
                //文本
                mimeMessageHelper.setText("<!DOCTYPE html><html><head><meta charset='utf-8'><title></title></head><body>" +
                        "<table>" +
                        "<tr><th>欢迎注册健身私教预约系统</th></tr>" +
                        "<tr><td>教练您好，您正在注册健身私教预约系统，已查验你提交的注册材料，经过审核注册失败，请补充认证材料。</td></tr>" +
                        "<tr><td>失败的原因是：" + msg + "</td></tr>" +
                        "<tr><td>现在时间：" + DateUtil.getTime() + "</td></tr>" +
                        "</table></body></html>", true);
            }
            mailSender.send(mimeMessage);
            log.info("发送邮件成功：发件人：{},收件人：{},主题：{},时间：{}", email, to, subject, DateUtil.getTime());
        } catch (MailSendException e) {
            Set<String> tmpInvalidMails = getInvalidAddress(e);
            // 非无效收件人导致的异常，暂不处理
            if (tmpInvalidMails.isEmpty()) {
                log.error(e.getMessage());
            }
            log.info("发送邮件失败：发件人：{},收件人：{},主题：{},时间：{},错误：{},结束：{}", email, to, subject, DateUtil.getTime(), e.getMessage(), "结束");
            return 0;
        }
        return 1;
    }

    private Set<String> getInvalidAddress(MailSendException e) {
        Set<String> mails = new HashSet<>();
        for (Exception exception : e.getFailedMessages().values()) {
            if (exception instanceof SendFailedException) {
                for (Address address : ((SendFailedException) exception).getInvalidAddresses()) {
                    mails.add(address.toString());
                }
            }
        }
        return mails;
    }
}
